import {getTargetData, IndexType, updateWeight, WeightVO} from '@/services/TargetWeightService'
import {message} from 'antd'
import dayjs from 'dayjs'
import {flow, makeAutoObservable, runInAction} from 'mobx'

export type WeightType = 'seller' | 'operation' | 'channel' | 'all_sales' | 'all_customer' | string

class TargetWeightModel {
    /**
     * 月份
     * @private
     */
    private month: string = dayjs().format('YYYY-MM')
    current: WeightVO[] = []
    allSalesTargetWeight: WeightVO = {
        currentPercentage: 0,
        currentTargetValue: 0,
        indexType: 'sales',
        month: this.month,
        name: '总业绩目标',
        percentage: 0,
        relationId: '0',
        target: 0,
        type: 'all_sales',
        unit: '元',
        width: 0,
    }
    allCustomerTargetWeight: WeightVO = {
        currentPercentage: 0,
        currentTargetValue: 0,
        indexType: 'customer',
        month: this.month,
        name: '总客资目标',
        percentage: 0,
        relationId: '0',
        target: 0,
        type: 'all_customer',
        unit: '个',
        width: 0,
    }
    sellerTargetWeight: WeightVO[] = []
    operationTargetWeight: WeightVO[] = []
    channelTargetWeight: WeightVO[] = []
    drawerState: boolean = false
    saveLoading = false

    get pageLoading() {
        return this.allCustomerTargetWeight.id === undefined
    }

    closeDrawerState() {
        this.drawerState = false
    }

    openDrawerState() {
        this.drawerState = true
    }

    get allSalesTarget() {
        return this.allSalesTargetWeight.target
    }

    get allCustomerTarget() {
        return this.allCustomerTargetWeight.target
    }

    weighDrawerState = false
    setAllSalesTarget = (e: any) => {
        if (!e.target.value) return
        this.allSalesTargetWeight.target = e.target.value
        this.allSalesTargetWeight.currentPercentage =
            Math.round((this.allSalesTargetWeight.currentTargetValue / this.allSalesTargetWeight.target) * 10000) / 100
        this.sellerTargetWeight.forEach(this.updateItem)
    }
    setAllCustomerTarget = (e: any) => {
        let value = e.target.value
        if (!value) return
        this.allCustomerTargetWeight.target = value
        this.allCustomerTargetWeight.currentPercentage =
            Math.round((this.allCustomerTargetWeight.currentTargetValue / this.allCustomerTargetWeight.target) * 10000) / 100
        this.channelTargetWeight.forEach(this.updateItem)
        this.operationTargetWeight.forEach(this.updateItem)
    }

    openWeighDrawerState() {
        this.weighDrawerState = true
    }

    closeWeighDrawerState() {
        this.weighDrawerState = false
    }

    constructor() {
        makeAutoObservable(this, {}, {autoBind: true})
    }

    fetchWeight = flow(
        function* () {
            // @ts-ignore
            let targetList: WeightVO[] = yield getTargetData({month: this.month})

            // @ts-ignore
            this.allSalesTargetWeight = targetList.find((item) => item.type === 'all_sales') || this.allSalesTargetWeight
            // @ts-ignore
            this.allCustomerTargetWeight =
                // @ts-ignore
                targetList.find((item) => item.type === 'all_customer') || this.allCustomerTargetWeight

            targetList.forEach((item) => {
                item.currentPercentage = Math.round((item.currentTargetValue / item.target) * 10000) / 100 || 0
                // @ts-ignore
                item.percentage = Math.round((item.target / this.getAllTargetByIndexType(item.indexType)) * 10000) / 100
            })

            // @ts-ignore
            this.sellerTargetWeight = targetList.filter((item) => item.type === 'seller')
            // @ts-ignore
            this.operationTargetWeight = targetList.filter((item) => item.type === 'operation')
            // @ts-ignore
            this.channelTargetWeight = targetList.filter((item) => item.type === 'channel')
            // @ts-ignore
            this.switchCurrentType('channel')
        }.bind(this),
    )

    /**
     * 切换数据源
     * @param type 类型
     */
    switchCurrentType(type: WeightType) {
        this.current = this.getWeightByType(type)
    }

    /**
     * 通过类型获取数据源
     * @param type 类型
     */
    getWeightByType(type: WeightType) {
        switch (type) {
            case 'seller':
                return this.sellerTargetWeight
            case 'operation':
                return this.operationTargetWeight
            case 'channel':
                return this.channelTargetWeight
            default:
                return this.channelTargetWeight
        }
    }

    getAllWeightByType(type: WeightType) {
        return Math.round(this.getWeightByType(type).reduce((acc, curr) => acc + (curr.percentage || 0), 0))
    }

    /**
     * 当前选中的数据源权重之和
     */
    get currentAllWeight() {
        return this.current.reduce((acc, curr) => acc + (curr.percentage || 0), 0)
    }

    /**
     * 设置权重
     * @param id unionId
     * @param value 百分数
     */
    setWeight(id: string, value: number) {
        let weightVO = this.current.find((w) => w.relationId === id)
        if (weightVO) {
            weightVO.percentage = value
        }
    }

    /**
     * 设置权重
     * @param type 数据源类型
     * @param id unionId
     * @param value 百分比
     */
    setWeightByType(type: WeightType, id: string, value: number) {
        let weightVO = this.getWeightByType(type).find((item) => item.relationId === id)
        if (!weightVO) return
        weightVO.percentage = value
        this.updateItem(weightVO)
    }

    /**
     * 更新单个项目的数值
     * @param weightVO 对象
     * @param type 类型
     */
    updateItem(weightVO: WeightVO) {
        let allTargetByIndexType = this.getAllTargetByIndexType(weightVO.indexType)
        weightVO.target = Math.round(allTargetByIndexType * weightVO.percentage * 0.01)
        weightVO.percentage = Math.round((weightVO.target / allTargetByIndexType) * 100) || 0
        weightVO.currentPercentage = Math.round((weightVO.currentTargetValue / weightVO.target) * 10000) / 100 || 0
    }

    /**
     * 更新权重Action
     */
    async updateData() {
        runInAction(() => (this.saveLoading = true))
        let data = [
            this.allCustomerTargetWeight,
            this.allSalesTargetWeight,
            ...this.channelTargetWeight,
            ...this.sellerTargetWeight,
            ...this.operationTargetWeight,
        ]
        data.forEach((item) => (item.month = this.month))
        updateWeight(data).then(() => {
            message.success('保存成功', 2)
            runInAction(() => {
                this.saveLoading = false
                this.drawerState = false
            })
        })
    }

    /**
     * 根据指标类型获取数据源
     * @param indexType
     */
    getAllTargetByIndexType(indexType: IndexType) {
        switch (indexType) {
            case 'sales':
                return this.allSalesTarget
            case 'customer':
                return this.allCustomerTarget
        }
    }
}

export default TargetWeightModel
export const targetWeightModel = new TargetWeightModel()
